// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === "extract") {
    const articleData = extractArticleData();
    sendResponse(articleData);
  } else if (request.action === "extractCover") {
    const coverData = extractCoverOnly();
    sendResponse(coverData);
  }
});

// 提取文章数据
function extractArticleData() {
  const data = {
    cover: '',
    keywords: '',
    title: '',
    content: '',
    url: window.location.href
  };

  // 提取封面图片
  const preloadLinks = document.querySelector('meta[name="og:image"]');
  if (preloadLinks) {
    data.cover = preloadLinks.content;
  }

  // 提取关键词
  const keywordsMeta = document.querySelector('meta[name="keywords"]');
  if (keywordsMeta) {
    data.keywords = keywordsMeta.content;
  }

  // 提取点赞数
  const likeMeta = document.querySelector('meta[name="og:xhs:note_like"]');
  if (likeMeta) {
    data.like = likeMeta.content;
  }

  // 提取评论数
  const commentMeta = document.querySelector('meta[name="og:xhs:note_comment"]');
  if (commentMeta) {
    data.comment = commentMeta.content;
  }

  // 提取收藏数
  const collectMeta = document.querySelector('meta[name="og:xhs:note_collect"]');
  if (collectMeta) {
    data.collect = collectMeta.content;
  }

  // 提取日期字符串
  const dateMeta = document.querySelector('.date');
  if (dateMeta) {
      const text = dateMeta.textContent.trim(); // 获取完整文本内容
      const match = text.match(/\d{2}-\d{2}/); // 匹配 "11-08 广东" 格式
      console.log(match);
      if (match) {
          data.date = match[0]; // 输出: "11-08 广东"
      }
  }

  // 提取标题
  const titleMeta = document.querySelector('meta[name="og:title"]');
  if (titleMeta) {
    const title = titleMeta.content;
    const firstSpaceIndex = title.indexOf(' - ');
    if (firstSpaceIndex !== -1) {
      data.title = title.substring(0, firstSpaceIndex);
    } else {
      data.title = title;
    }
  }

  // 提取标题和正文
  const descriptionMeta = document.querySelector('meta[name="description"]');
  if (descriptionMeta) {
    const content = descriptionMeta.content;
    data.content = content;
  }

  return data;
}

// 只提取封面图片
function extractCoverOnly() {
  const preloadLinks = document.querySelector('meta[name="og:image"]');
  if (preloadLinks) {
    return {
      cover: preloadLinks.content,
    };
  }
  return {
    cover: '',
  };
}
